'use strict';

const Service = require('egg').Service;

class ExperienceCommentService extends Service {
  // 根据经验ID获取评论
  async findByExperienceId(experienceId) {
    const { ctx } = this;
    
    // 获取所有评论（包括回复）
    const comments = await ctx.model.ExperienceComment.findAll({
      where: { experience_id: experienceId },
      order: [['created_at', 'ASC']],
    });

    // 构建评论树结构
    const commentMap = {};
    const rootComments = [];

    // 第一遍遍历：创建映射
    comments.forEach(comment => {
      commentMap[comment.comment_id] = {
        ...comment.toJSON(),
        replies: []
      };
    });

    // 第二遍遍历：构建树结构
    comments.forEach(comment => {
      const commentData = commentMap[comment.comment_id];
      if (comment.parent_id) {
        // 这是一个回复
        if (commentMap[comment.parent_id]) {
          commentMap[comment.parent_id].replies.push(commentData);
        }
      } else {
        // 这是一个根评论
        rootComments.push(commentData);
      }
    });

    return rootComments;
  }

  // 创建评论
  async create(data) {
    const { ctx } = this;
    return await ctx.model.ExperienceComment.create(data);
  }

  // 获取评论数量
  async getCommentCount(experienceId) {
    const { ctx } = this;
    return await ctx.model.ExperienceComment.count({
      where: { experience_id: experienceId }
    });
  }
}

module.exports = ExperienceCommentService;
